<template>
  <view class="container">
    <view class="form-content">
      <!-- Order No Field -->
      <view class="form-group">
        <text class="label">订单NO</text>
        <view class="input-container">
          <view class="input-wrapper">
            <input 
              ref="orderNoInput"
              class="input" 
              type="text" 
              v-model="inputOrderNo"
              @input="onOrderInput"
              @confirm="onOrderConfirm"
              placeholder="请扫描订单号"
              :focus="focusedField === 'orderNo'"
              confirm-type="next"
              :cursor-spacing="0"
              :adjust-position="false"
              hold-keyboard="false"
              inputmode="none"
            />
            <view v-if="inputOrderNo && inputOrderNo.trim().length > 0" class="clear-btn" @click="onOrderNoClear">
              <text class="clear-icon">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- Machine ID Field -->
      <view class="form-group">
        <text class="label">实装机ID</text>
        <view class="input-container">
          <view class="input-wrapper">
            <input 
              ref="machineIdInput"
              class="input" 
              type="text" 
              v-model="inputMachineId"
              @confirm="onScanConfirm('machineId')"
              placeholder="请扫描实装机ID"
              :focus="focusedField === 'machineId'"
              confirm-type="next"
              :cursor-spacing="0"
              :adjust-position="false"
              hold-keyboard="false"
              inputmode="none"
            />
            <view v-if="inputMachineId && inputMachineId.trim().length > 0" class="clear-btn" @click="onMachineIdClear">
              <text class="clear-icon">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- Surface Field -->
      <view class="form-group">
        <text class="label">实装面</text>
        <view class="input-container">
          <view class="input-wrapper">
            <input 
              ref="surfaceInput"
              class="input" 
              type="text" 
              v-model="inputSurface"
              @confirm="onScanConfirm('surface')"
              @input="onSurfaceInput"
              placeholder="请扫描实装面"
              :focus="focusedField === 'surface'"
              confirm-type="done"
              :cursor-spacing="0"
              :adjust-position="false"
              hold-keyboard="false"
              inputmode="none"
              maxlength="1"
            />
            <view v-if="inputSurface && inputSurface.trim().length > 0" class="clear-btn" @click="onSurfaceClear">
              <text class="clear-icon">×</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="button-group">
      <button class="btn btn-back" @click="onBack">返回</button>
      <button class="btn btn-start" @click="onStart">开始</button>
    </view>
  </view>
</template>

<script>
// 使用UniApp兼容的网络请求工具
import { initiatePickup } from '@/api/smt';
// 导入通用扫码处理工具
import { ScanHandler, parseOrderScanData, FocusManager } from '@/utils/scanHandler';
// 导入双缓存系统
import { setBaseCacheData, clearAllCacheData } from '@/utils/cacheManager';

export default {
  data() {
    return {
      // Data for input fields
      inputOrderNo: '',
      inputMachineId: '',
      inputSurface: '',
      
      focusedField: 'orderNo', // Track which field is currently focused
      
      // 扫码处理器
      scanHandler: null,
      focusManager: null
    };
  },
  mounted() {
    // 初始化扫码处理器和焦点管理器
    this.initializeScanHandler();
    this.initializeFocusManager();
    
    // 页面加载完成后设置焦点到第一个输入框
    setTimeout(() => {
      this.focusFirstInput();
    }, 300);
  },
  beforeDestroy() {
    // 清理扫码处理器
    if (this.scanHandler) {
      this.scanHandler.destroy();
    }
    if (this.focusManager) {
      this.focusManager.destroy();
    }
  },
  methods: {
    // 初始化扫码处理器
    initializeScanHandler() {
      this.scanHandler = new ScanHandler({
        minScanLength: 18, // 保持最小长度检查，确保订单码完整性
        onScanComplete: (scanValue) => {
          this.handleOrderScan(scanValue);
        },
        onScanError: (error, scanValue) => {
          console.error('扫码处理错误:', error);
          uni.showToast({
            title: '扫码处理失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 初始化焦点管理器
    initializeFocusManager() {
      this.focusManager = new FocusManager();
    },
    
    // 处理订单扫码
    handleOrderScan(scanValue) {
      const parseResult = parseOrderScanData(scanValue);
      
      if (!parseResult.success) {
        uni.showToast({
          title: parseResult.error,
          icon: 'none',
          duration: 2000
        });
        
        // 清空所有字段并重新聚焦
        this.clearAllFields();
        setTimeout(() => {
          this.focusFirstInput();
        }, 2100);
        return;
      }
      
      // 解析成功，填充字段
      const { orderNo, machineId, surface } = parseResult.data;
      this.inputOrderNo = orderNo; // 只保留-01前的部分
      this.inputMachineId = machineId;
      this.inputSurface = surface;
      
      // 成功反馈
      uni.showToast({
        title: '扫描成功',
        icon: 'success',
        duration: 1000
      });
      
      // 移除焦点，让用户可以点击开始按钮
      setTimeout(() => {
        this.focusedField = null;
      }, 1500);
    },
    
    onBack() {
      uni.redirectTo({
        url: '/pages/menu/menu'
      });
    },
    // 设置焦点到第一个输入框
    focusFirstInput() {
      // 使用UniApp推荐的方式：通过更新focusedField来触发重新聚焦
      // 先清除焦点，再设置焦点以确保触发focus属性的变化
      this.focusedField = null;
      this.$nextTick(() => {
        this.focusedField = 'orderNo';
      });
    },
    
    // 订单号输入处理 - 实时更新扫码缓冲区
    onOrderInput(e) {
      if (this.scanHandler) {
        this.scanHandler.handleInput(e.target.value.trim());
      }
    },
    
    // 订单号确认处理（回车键按下时）- PDA的最后一个回车触发分割
    onOrderConfirm() {
      if (this.scanHandler && this.inputOrderNo.trim()) {
        this.scanHandler.handleConfirm(this.inputOrderNo.trim());
      }
    },
    
    // 实装面输入校验
    onSurfaceInput(e) {
      const value = e.target.value;
      // 校验实装面长度不超过1个字符
      if (value.length > 1) {
        this.inputSurface = value.charAt(0); // 只保留第一个字符
        uni.showToast({
          title: '实装面只能输入1个字符',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    async onStart() {
      // 验证所有字段都已输入
      if (!this.inputOrderNo || !this.inputMachineId || !this.inputSurface) {
        uni.showToast({
          title: '请完成所有字段输入',
          icon: 'none',
          duration: 2000
        });
        // 重新设置焦点到第一个输入框 - 在Toast消失后立即聚焦
        setTimeout(() => {
          this.focusFirstInput();
        }, 2100);
        return;
      }
      
      // 验证实装面长度
      if (this.inputSurface.length !== 1) {
        uni.showToast({
          title: '实装面必须是1个字符',
          icon: 'none',
          duration: 2000
        });
        this.focusedField = 'surface';
        return;
      }
      
      // 清理所有缓存数据
      try {
        clearAllCacheData();
        console.log('✅ 已清理所有缓存数据');
      } catch (clearError) {
        console.error('❌ 清理缓存失败:', clearError);
      }
      
      // 准备调用后端接口的数据
      const payload = {
        orderNo: this.inputOrderNo,
        orderBranchNo: '01', // 固定值
        mounterId: this.inputMachineId,
        smtSide: this.inputSurface
      };

      uni.showLoading({
        title: '加载中...'
      });

      try {
        // 调用后端 API
        const res = await initiatePickup(payload);

        uni.hideLoading();

        // 检查 HTTP 状态码 (uni.request 返回 statusCode)
        // 主要逻辑判断放在 RespBean 的 code 上
        if (res.statusCode === 200) {
          const respBean = res.data;
          
          // 检查业务逻辑是否成功 (RespBean.code === '00000')
          if (respBean && respBean.code === '00000') {
            // 成功：将返回的数据存入双缓存系统的本地缓存①
            try {
              const baseData = {
                lineId: respBean.data.lineId || '',
                mounterId: this.inputMachineId,
                operatorId: '', // 将在作业员确认页面填入
                orderBranchNo: '01',
                orderNo: this.inputOrderNo,
                smtSide: this.inputSurface,
                partList: respBean.data.partList || []
              };
              
              const success = setBaseCacheData(baseData);
              if (!success) {
                throw new Error('设置基础缓存数据失败');
              }
              
              console.log('✅ 基础数据已保存到本地缓存①:', baseData);
              
              // 跳转到作业员确认页面
              uni.navigateTo({
                url: '/pages/operator-confirm/operator-confirm'
              });
            } catch (storageError) {
              console.error('❌ 缓存数据失败:', storageError);
              uni.showToast({
                title: '数据缓存失败，请重试',
                icon: 'none',
                duration: 2000
              });
            }
          } else {
                  // 业务逻辑错误
                  const errorMsg = respBean.message || '操作失败';
                  uni.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 2000
                  });
                  // 清空扫描输入框，让用户重新扫描
                  setTimeout(() => {
                    this.focusFirstInput();
                  }, 2100);
                }
        } else {
          // HTTP 错误
          uni.showToast({
            title: `请求失败 (${res.statusCode})`,
            icon: 'none',
            duration: 2000
          });
          // 重新设置焦点
          setTimeout(() => {
            this.focusFirstInput();
          }, 2100);
        }
      } catch (error) {
        // 网络错误或其他异常
        uni.hideLoading();
        
        // 显示用户友好的错误信息，优先使用uniRequest设置的userMessage
        let errorMessage = error.userMessage || error.message || '程序选择失败，请重试';
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
        // 重新设置焦点
        setTimeout(() => {
          this.focusFirstInput();
        }, 3100);
      }
    },
    
    // 原生清除按钮事件处理
    onOrderNoClear() {
      this.inputOrderNo = '';
      this.focusFirstInput();
    },
    
    onMachineIdClear() {
      this.inputMachineId = '';
      this.focusedField = 'machineId';
    },
    
    onSurfaceClear() {
      this.inputSurface = '';
      this.focusedField = 'surface';
    },
    
    clearAllFields() {
      this.inputOrderNo = '';
      this.inputMachineId = '';
      this.inputSurface = '';
      // 重新设置焦点到订单号
      this.focusFirstInput();
    }
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - var(--window-top));
  background-color: #f2f2f2;
}
.form-content {
  flex: 1;
  padding: 20px;
}
.form-group {
  margin-bottom: 15px;
}
.label {
  display: block;
  margin-bottom: 5px;
}
.input {
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
  height: 38px;
}

/* 输入框容器和清除按钮样式 */
.input-wrapper {
  position: relative;
  width: 100%;
}

.clear-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.clear-btn:hover {
  background-color: #999;
}

.clear-icon {
  color: white;
  font-size: 14px;
  font-weight: bold;
  line-height: 1;
}
.medium {
  width: 70%;
}
.input-container {
  position: relative;
}
.button-group {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  background-color: #f2f2f2;
}
.btn {
  width: 48%; /* Adjusted for two buttons */
  height: 50px;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  transition: all 0.2s;
}

.btn:active {
  transform: translateY(2px);
  box-shadow: 0 1px 2px rgba(0,0,0,0.2);
}

.btn-back {
  background-color: #607D8B; /* 蓝灰色 - 低调的辅助功能 */
  color: white;
  border: 1px solid #546E7A;
}

.btn-back:hover {
  background-color: #546E7A;
  transform: translateY(1px);
}

.btn-back:active {
  background-color: #455A64;
  transform: translateY(2px);
}

.btn-start {
  background-color: #4CAF50;
  color: white;
}
</style>